<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="套餐名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入套餐名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:setmeal:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          :disabled="multiple"
          @click="handleStatus(1)"
        >批量起售</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          size="mini"
          :disabled="multiple"
          @click="handleStatus(0)"
        >批量停售</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:setmeal:remove']"
        >删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="setmealList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="套餐名称" align="center" prop="name" />
      <el-table-column label="套餐分类" align="center" prop="categoryName"/>
      <el-table-column label="套餐价格" align="center" prop="price" />
      <el-table-column label="售卖状态" align="center" prop="status">
        <template slot-scope="scope">
            <el-tag v-if="scope.row.status==0">停售</el-tag>
          <el-tag v-else>在售</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="最后操作时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:setmeal:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:setmeal:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改套餐对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="套餐分类" prop="categoryId">
          <el-select v-model="form.categoryName" placeholder="请选择套餐分类">
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="套餐价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入套餐价格" />
        </el-form-item>


        <el-form-item label="套餐菜品" >
          <el-button type="primary" icon="el-icon-plus" @click="openAddDish">添加</el-button>
          <el-table
            :data="selectDishList"
            style="width: 100%">

            <el-table-column
              prop="label"
              label="名称"
              width="180">
            </el-table-column>
            <el-table-column
              prop="price"
              label="原价"
              width="180">
            </el-table-column>
            <el-table-column
              prop="copies"
              label="份数">
              <template slot-scope="scope">
                <el-input-number
                  size="small"
                  v-model="scope.row.copies" :min="1" :max="10" label="请选择份数"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column
              label="操作">
              <template slot-scope="scope">
              <el-button
                type="text"
                style="color: red"
                size="small"
                icon="el-icon-delete"
                @click="deletesd(scope.$index)"
              >删除
              </el-button>
              </template>
            </el-table-column>

          </el-table>
        </el-form-item>

        <el-form-item label="图片">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="描述信息" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加菜品" :visible.sync="dialogVisible"width="800px">
      <div style="text-align: center">
        <el-transfer
          style="text-align: left; display: inline-block"
          v-model="value"
          filterable
          :titles="['未选菜品', '已选菜品']"
          filter-placeholder="请输入菜品名"
          :data="dataT">
        </el-transfer>
      </div >

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="quTransfer">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listSetmeal, getSetmeal, delSetmeal, addSetmeal, updateSetmeal ,updateSetmealStatus} from "@/api/system/setmeal";
import { listCategory } from "@/api/system/category";
import { listDish} from "@/api/system/dish";
import {listSetmealDish } from "@/api/system/setmealdish";
import {dataTool} from "echarts/lib/echarts";
export default {
  name: "Setmeal",
  data() {
    return {
      dataT: [],
      value: [],
      dialogVisible: false,
      setmeaDishList: [],
      selectDishList: [],

      categoryList: [],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 套餐表格数据
      setmealList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        categoryName: [
          { required: true, message: "套餐分 类不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "套餐名称不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "套餐价格不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getCategoryList();
  },
  methods: {
    // type 1:查询菜品的id 2:修改的dishId
    toMap(data, type) {
      // 数据转换
      console.log("toMap:data:::");
      console.log(data)
      const transferData = data.map(item => ({
        key: type == 1 ? item.id : item.dishId,
        price: item.price,
        label: item.name,
        dishId: item.dishId,
        id: item.id,
        copies: item.copies
      }))
      console.log("toMap:transferData:::");
      console.log(transferData)
      return transferData;
    },

    deletesd(index) {
      this.selectDishList.splice(index,1)
    },

    quTransfer() {
      // 添加新的 (为了保证原来的数据不改变)
      let va = this.value;
      //左移执行 这个代码就是解决穿梭款往左移动(两个进行匹配然后过滤调不匹配的元素)
      this.selectDishList = this.selectDishList.map(item => {
        if (va.includes(item.key)) {
          return item;
        } else {
          return null;
        }
      }).filter(item => item !== null);

      console.log("value::::");
      console.log(this.value);
      //2. 通过截取选中的菜品 > 把以前选中的菜品删除
      this.value.splice(0, this.selectDishList.length);

      //1. 循环新选中的菜品，并追加到tabel列表
      this.value.forEach(items => {
        // 获取到菜品信息
        const obj = this.dataT.find((obj) => obj.key === items);
        this.selectDishList.push(obj);
      })

      this.dialogVisible = false;
    },

    // 通过套餐ID获取菜品列表分类
    getDishLists() {
      listDish().then(resp => {
        //穿梭款的所有值
        this.dataT = this.toMap(resp.rows, 1);
      })
    },


    // 添加菜品按钮
    openAddDish() {
      this.dialogVisible = true;
      this.getDishLists()
      // 下面的代码是重新打开穿梭框时，将选中的数据(selectDishList)再次赋值
      // value 重置
      this.value = [];
      //新的追加 选中(穿梭款) value
      this.selectDishList.forEach(dt => {
        this.value.push(dt.key)
      });
    },


    getCategoryList() {
      this.loading = true;
      listCategory({type:2}).then(response => {
        this.categoryList = response.rows;
        this.loading = false;
      });
    },

    /** 查询套餐列表 */
    getList() {
      this.loading = true;
      listSetmeal(this.queryParams).then(response => {
        this.setmealList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.selectDishList = [];
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        categoryId: null,
        name: null,
        price: null,
        status: 0,
        code: null,
        description: null,
        image: null,
        createTime: null,
        updateTime: null,
        createUser: null,
        updateUser: null,
        isDeleted: null,
        categoryName: null,
        setmealDishes:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery(){
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getCategoryList();
      this.open = true;
      this.title = "添加套餐";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getCategoryList();
      const id = row.id || this.ids
      getSetmeal(id).then(response => {
        this.form = response.data;
        this.selectDishList = this.toMap(this.form.setmealDishes, 2);
        console.log("select:Update::");
        console.log(this.selectDishList);
        this.open = true;
        this.title = "修改套餐";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //将数据转换成后端认识的数据
          let setmealArr = []
          this.selectDishList.forEach(item=>{
            setmealArr.push({
              id: item.id,
              dishId: item.dishId == null ? item.key : item.dishId,
              name: item.label,
              price: item.price,
              copies: item.copies
            })
          })
          console.log("setmealArr::::")
          console.log(setmealArr)
          this.form.setmealDishes = setmealArr;
          if (this.form.id != null) {
            this.categoryNameIsNum();
            console.log("update ::form");
            console.log(this.form)
            updateSetmeal(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.categoryNameIsNum();
            addSetmeal(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    categoryNameIsNum() {
      let flag = /^[0-9]/;
      if (flag.test(this.form.categoryName)){
        this.form.categoryId = this.form.categoryName;
      }
    },


    handleStatus(status) {
      const ids = this.ids;
      let flag = status == 0 ? '停售' : '起售';
      this.$modal.confirm('是否确认' + flag + '套餐编号为"' + ids + '"的数据项？').then(function () {
        return updateSetmealStatus(ids, status);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("更新成功");
      }).catch(() => {
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除套餐编号为"' + ids + '"的数据项？').then(function() {
        return delSetmeal(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/setmeal/export', {
        ...this.queryParams
      }, `setmeal_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
